#include <stdbool.h>
#include <stdint.h>

#include "tgtdefs.h"
#include "nRF24L.h"

#include "ctrl_settings.h"
/*
// size of these is 256 bytes
#define NV_DATA_EXT_END0_ADDR		((__xdata uint8_t*) 0xfa00)
#define NV_DATA_EXT_END0_PAGE_NUM	32
#define NV_DATA_EXT_END1_ADDR		((__xdata uint8_t*) 0xfb00)
#define NV_DATA_EXT_END1_PAGE_NUM	33
*/
// size of these is 512 bytes
#define NV_DATA_NORM_END0_ADDR		((__xdata uint8_t*) 0xfc00)
#define NV_DATA_NORM_END0_PAGE_NUM	34
#define NV_DATA_NORM_END1_ADDR		((__xdata uint8_t*) 0xfe00)
#define NV_DATA_NORM_END1_PAGE_NUM	35

__xdata uint8_t* pCurrOutputPower = NV_DATA_NORM_END0_ADDR;

//void list_page(void)
//{
//	__xdata uint8_t* ptr = NV_DATA_NORM_END0_ADDR;
//	while (ptr < NV_DATA_NORM_END1_ADDR)
//	{
//		printf("%02x ", *ptr++);
//		if (((uint16_t) ptr & 0x0f) == 0)
//			putchar('\n');
//	}
//}

static void flash_page_erase(uint8_t pn)
{
    WEN = 1;	// enable flash write
    FCR = pn;	// page number to erase
    WEN = 0;	// disable flash write
}

uint8_t get_nrf_output_power(void)
{
	uint8_t ret_val;
	
	// find the last valid (non 0xff) byte in the page
	while (pCurrOutputPower < NV_DATA_NORM_END1_ADDR  &&  pCurrOutputPower[1] != 0xff)
		++pCurrOutputPower;

	ret_val = *pCurrOutputPower;
	
	// default to highest power
	if (ret_val != vRF_PWR_M18DBM
			&&  ret_val != vRF_PWR_M12DBM
			&&  ret_val != vRF_PWR_M6DBM)
	{
		ret_val = vRF_PWR_0DBM;
	}

	return ret_val;
}

void set_nrf_output_power(uint8_t new_val)
{
	if (new_val != vRF_PWR_M18DBM
			&&  new_val != vRF_PWR_M12DBM
			&&  new_val != vRF_PWR_M6DBM)
	{
		new_val = vRF_PWR_0DBM;
	}
	
	// if the new value is different than the old one
	if (*pCurrOutputPower != new_val)
	{
		// find the first unused byte in the page
		while (pCurrOutputPower < NV_DATA_NORM_END1_ADDR  &&  *pCurrOutputPower != 0xff)
			++pCurrOutputPower;

		// if the page is full
		if (pCurrOutputPower == NV_DATA_NORM_END1_ADDR)
		{
			// erase the page and start from the beginning
			flash_page_erase(NV_DATA_NORM_END0_PAGE_NUM);
			pCurrOutputPower = NV_DATA_NORM_END0_ADDR;
		}
		
		// save the value
		WEN = 1;
		PCON &= ~_BV(4);	// clear PMW
		*pCurrOutputPower = new_val;
		WEN = 0;
	}
}
